package models

import (
	"time"

	"gitee.com/yizhongi/wfw/util"
	"github.com/beego/beego/v2/adapter/logs"
	"github.com/beego/beego/v2/adapter/orm"
	"github.com/beego/beego/v2/core/config"
	_ "github.com/beego/beego/v2/core/config/xml"

	_ "github.com/mattn/go-sqlite3" //sqlite 驱动
)

func init() {
	//设置数据库连接信息
	orm.RegisterDataBase("default", "sqlite3", "data.db")
	orm.DefaultTimeLoc = time.UTC
	// 如果是开发模式， 则显示命令信息
	dev, _ := config.String("runmode")
	isDev := (dev == "dev")
	// 映射modle数据
	orm.RegisterModel(new(User), new(Store), new(Port), new(Volume), new(DeployTask), new(TaskRun), new(AppLog))
	// 非强制模式下自动建表
	// 生成表，第二个false要是改成true 就会强制更新表，数据全部丢失
	err := orm.RunSyncdb("default", false, isDev)
	if err != nil {
		logs.Informational("[orm] Create table err : ", err)
	}
	if isDev {
		orm.Debug = isDev
	}
	initAdminUser()
}

func initAdminUser() {
	o := orm.NewOrm()
	user := User{Username: "admin", Password: util.Md5Pwd("ed#16888")}
	if created, id, err := o.ReadOrCreate(&user, "Username"); err == nil {
		if created {
			logs.Debug("New Insert an object. Id:", id)
		} else {
			logs.Debug("Get an object. Id:", id)
		}
	}
}
